<?php
/**
 * Created by Silent Night.
 * Author: Silent Night
 * email: silentwolf_wp@163.com
 * Date: 2017/9/28
 * Time: 9:36
 */

namespace app\admin\model;

use think\Db;
use think\Model;
use think\Request;
use think\Validate;

class Admin extends Model{

    protected $field = [
        'id'      => '编号',
        'username' => '用户名',
        'name'   => '昵称',
        'avatar'   => '头像',
        'email'     => '邮箱',
        'password'   => '密码',
        'salt' => '字符串',
        'join_ip'  => '最后登录ip',
        'active'  => '有效',
        'created_at'  => '创建时间',
        'updated_at'    => '更新时间',
    ];
    protected $rule = [
        'username' => "require|unique:admin",  //必填。
        'email'     => "require|email|unique:admin",  //必填。
        'mobile'     => "require|email|unique:admin",  //必填。
        'password'   => 'require',
    ];

    /**
     * 验证数据
     * @return array
     */
    public function valid(){
        $data = input('post.');
        $validate = new Validate($this->rule, [ ], $this->field);
        $res = $validate->check($data);
        //验证字段
        if($res == false){
            $this->_error = $validate->getError();

            return array( 'err' => 1, 'msg' => $this->_error );
        }else{
            return array( 'err' => 0 );
        }
    }

    /**
     * 随机字符
     * @param number $length 长度
     * @param string $type 类型
     * @param number $convert 转换大小写
     * @return string
     */
    function random($length=4, $type='string', $convert=0){
        $config = array(
            'number'=>'1234567890',
            'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
            'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
            'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
        );

        if(!isset($config[$type])) $type = 'string';
        $string = $config[$type];

        $code = '';
        $strlen = strlen($string) -1;
        for($i = 0; $i < $length; $i++){
            $code .= $string{mt_rand(0, $strlen)};
        }
        if(!empty($convert)){
            $code = ($convert > 0)? strtoupper($code) : strtolower($code);
        }
        return $code;
    }

    /**
     * 列表数据
     */
    public function getLists()
    {
        return $this->select();
    }

    /**
     * 注册数据
     */
    public function register(){
        $data = input('post.');
        $data['salt'] = $this->random(4);
        $data['password'] = md5($data['password'].$data['salt']);
        $request = Request::instance();
        $data['join_ip'] = $request->ip();
        $data['created_at'] = $request->time();
        $data['updated_at'] = $request->time();
        return $this->allowField(true)->save($data);
    }

    /**
     * 编辑根据id获取全部数据
     */
    public function getListById()
    {
        return $this->where([ 'id' => input('id') ])->find()->toArray();
    }

    /**
     * 编辑用户
     */
    public function edit()
    {
        $data = input('post.');
        $data['updated_at'] = time();
        return $this->allowField(true)->save($data, [ 'id' => input('post.id')]);
    }

    /**
     * 删除用户
     */
    public function delete()
    {
        return $this->where('id', 'in', input('id'))->delete();
    }

    /**
     * 获取所有角色
     */
    public function getAllRole()
    {
        return Db::table('role')->select();
    }

    /**
     * 获取该用户角色
     */
    public function getAdminRole()
    {
        $id = input('id');
        $adminHasRole = Db::table('admin')
            ->join('admin_has_role','admin.id=admin_has_role.admin_id')
            ->join('role','admin_has_role.role_id=role.id')
            ->where(['admin.id'=>$id])
            ->field(['role.name','role.id'])
            ->select();
        $name = [];
        foreach ($adminHasRole as $item) {
            $name[] = $item['id'];
        }
        return $name;
    }

    /**
     * 设置用户角色
     */
    public function setRole()
    {
        $id = input('id');
        $data = input('post.');
        Db::table('admin_has_role')->where(['admin_id'=>$id])->delete();
        foreach ($data as $item)
        {
            Db::table('admin_has_role')->insert([
                'admin_id'=>$id,
                'role_id'=>$item,
            ]);
        }
        return true;
    }

    /**
     * 根据用户id判断权限路由
     * @param $id
     * @return false|mixed|\PDOStatement|string|\think\Collection
     */
    public function getAdminPower($id)
    {
        $adminHasRole = Db::table('admin_has_role')
            ->where(['admin_has_role.admin_id'=>$id])->select();
        $adminIds = [];
        foreach ($adminHasRole as $item) {
            $adminIds[] = $item['role_id'];
        }
        $powerHasRole = Db::table('power_has_role')
            ->whereIn('role_id',$adminIds)->select();
        $powerIds = [];
        foreach ($powerHasRole as $value) {
            $powerIds[] = $value['power_id'];
        }
        $powerUrls = Db::table('power')->whereIn('id',$powerIds)->select();
        return $powerUrls;
    }
}

